<template>
	<div class="system-user-container">
		<el-card class="box-card">
			<div>
				<div class="my_btn_lay">
					<div class="my_flex my_btn" @click="searchEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--search"></i>
							<span>查找</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="resetEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--refresh"></i>
							<span>重置</span>
						</div>
					</div>

					<!-- <div class="my_flex my_btn ml20" @click="addDefaultBlank">
						<div class="my_flex_layout">
							<i class="vxe-icon--plus"></i>
							<span>新增</span>
						</div>
					</div> -->

					<!-- <div class="my_flex my_btn ml20" @click="deleteTable">
						<div class="my_flex_layout">
							<i class="fa fa-trash-o"></i>
							<span>删除</span>
						</div>
					</div> -->

					<div class="my_flex my_btn ml20" @click="funnelEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--download"></i>
							<span>导出</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="printTab">
						<div class="my_flex_layout">
							<i class="vxe-icon--print"></i>
							<span>打印</span>
						</div>
					</div>
				</div>

				<vxe-form :data="selectFrom" title-align="left" prevent-submit title-colon>
					<vxe-form-item title="工程类别" field="engineeringTypeId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.engineeringTypeId" placeholder="请选择工程类别">
								<el-option v-for="item in selectFrom.engineeringTypeIdData" :key="item.id" :label="item.type" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="项目" field="contractId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.contractId" placeholder="请选择项目">
								<el-option v-for="item in selectFrom.contractIdData" :key="item.id" :label="item.contractName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="甲方合同单位" field="contractUnitId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.contractUnitId" placeholder="请选择甲方合同单位">
								<el-option v-for="item in selectFrom.contractUnitIdData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>
					<vxe-form-item title="项目经理" field="managerId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.managerId" placeholder="请选择项目经理">
								<el-option v-for="item in selectFrom.managerIdData" :key="item.id" :label="item.contactPerson" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="合作方" field="partnerId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.partnerId" placeholder="请选合作方">
								<el-option v-for="item in selectFrom.partnerIdData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="状态" field="state" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.state" placeholder="请选择状态">
								<el-option v-for="item in selectFrom.stateData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="收款开始时间" field="time" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time1" type="date" placeholder="本期收款开始时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<vxe-form-item title="收款结束时间" field="time" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time2" type="date" placeholder="本期收款结束时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<!-- <vxe-form-item align="right" span="24" collapse-node>
						<template #default>
							<vxe-button status="primary" content="搜索" @click="searchEvent"></vxe-button>
							<vxe-button content="重置" @click="resetEvent"></vxe-button>
						</template>
					</vxe-form-item> -->
				</vxe-form>
			</div>

			<!-- <vxe-toolbar ref="xToolbar" custom>
				<template #buttons>
					<vxe-button type="text" icon="fa fa-plus" content="新增" @click="addDefaultBlank"></vxe-button>
					<vxe-button type="text" icon="fa fa-trash-o" content="删除" @click="deleteTable"></vxe-button>
				</template>
				<template #tools>
					<vxe-button type="text" icon="vxe-icon--print" class="tool-btn" @click="printTab"></vxe-button>
					<vxe-button type="text" icon="vxe-icon--download" class="tool-btn" @click="funnelEvent"></vxe-button>
				</template>
			</vxe-toolbar> -->

			<!-- @edit-closed="editClosedEvent" -->
			<!-- :edit-config="{ trigger: 'click', mode: 'row' }" -->
			<vxe-table
				align="center"
				class="mytable-style"
				:scroll-x="{ enabled: false }"
				:scroll-y="{ enabled: false }"
				height="730"
				border
				keep-source
				ref="xTable1"
				:export-config="{}"
				resizable
				show-overflow
				:data="tableData"
				@checkbox-all="selectAllChangeEvent1"
				@checkbox-change="selectChangeEvent1"
			>
				<!-- <vxe-column type="checkbox" align="center"  fixed="left" width="60"></vxe-column> -->
				<vxe-column type="seq" align="center" title="序号"   fixed="left"  width="60"></vxe-column>

				<vxe-column width="80" field="engineeringType" title="工程类别" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="130" field="contractUnit" title="甲方名称" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="130" field="contractName" title="项目名称 " :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="80" field="projectManager" title="项目经理" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="80" field="state" title="工程状态" :edit-render="{ name: '$select', options: selectFrom.stateData }"></vxe-column>

				<vxe-column width="130" field="partnerUnit" title="合作方" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<!-- <vxe-column width="130" field="managementFee" title="管理费%" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column> -->
				<vxe-column width="80" field="managementFee"  title="管理费%" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-input v-model="scope.row.managementFee" placeholder="请输入数值类型" @change="change_sunbillMoney(scope.row)">
							<template #append>%</template>
						</el-input>
					</template>
					<template v-slot="{ row }">{{ row.managementFee }}%</template>
				</vxe-column>

				<vxe-column width="105" field="startTime" title="开工时间" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="105" field="endTime" title="竣工日期" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="100" field="warrantyPeriod" title="质保期" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="100" field="engineeringContractMoney" title="合同金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.engineeringContractMoney) }}</template>
				</vxe-column>
				<vxe-column width="110" field="supplementalAgreementMoney" title="补充协议金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.supplementalAgreementMoney) }}</template>
				</vxe-column>
				<vxe-column width="100" field="contractSubtotal" title="合同小计" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.contractSubtotal) }}</template>
				</vxe-column>
				<vxe-column width="100" field="settleAccount" title="结算金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.settleAccount) }}</template>
				</vxe-column>
				<vxe-column width="110" field="countProgress" title="累计上报产值" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.countProgress) }}</template>
				</vxe-column>
				<vxe-column width="100" field="receiptOfTheCurrentPeriod" title="本期收款" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.receiptOfTheCurrentPeriod) }}</template>
				</vxe-column>
				<vxe-column width="100" field="accumulativeCollection" title="累计收款" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.accumulativeCollection) }}</template>
				</vxe-column>
				<vxe-column width="100" field="uncollected" title="未收款" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.uncollected) }}</template>
				</vxe-column>
				<vxe-column width="100" field="managementFeeAccount" title="管理费" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.managementFeeAccount) }}</template>
				</vxe-column>
				<vxe-column width="100" field="collectionRate" title="回款率" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="100" field="remark" title="备注" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
			</vxe-table>
		</el-card>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, ref, toRaw, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
	axios_contractselListTop,
	axios_loanselList,
	axios_loanadd,
	axios_loanup,
	axios_loandel,
	axios_receivablesselList,
	axios_categoryselList,
	axios_SelList,
} from '/@/api/basicsUrl/index';

import { GenNonDuplicateID } from '/@/utils/formatTime';
import { transitionNumber } from '/@/utils/transitionNumber';

export default {
	name: 'ReceiptDetails',
	setup() {
		const xTable1 = ref({} as VxeTableInstance);
		const xToolbar = ref({} as VxeToolbarInstance);

		// 打印样式
		// 打印样式
		const printStyle = `
            .title {
              text-align: center;
            }
            .my-list-row {
              display: inline-block;
              width: 100%;
            }
            .my-list-col {
              float: left;
              width: 33.33%;
              height: 28px;
              line-height: 28px;
            }
            .my-top,
            .my-bottom {
              font-size: 12px;
            }
            .my-top {
              margin-bottom: 5px;
            }
            .my-bottom {
              margin-top: 30px;
              text-align: right;
            }
            `;

		// 打印顶部内容模板
		const topHtml = `
            <h1 class="title">出货单据</h1>
            <div class="my-top">
              <div class="my-list-row">
                <div class="my-list-col">商品名称： </div>
                <div class="my-list-col">发货单号：X2665847132654</div>
                <div class="my-list-col">发货日期：2020-09-20</div>
              </div>
              <div class="my-list-row">
                <div class="my-list-col">收货姓名： </div>
                <div class="my-list-col">收货地址：火星第七区18号001</div>
                <div class="my-list-col">联系电话：10086</div>
              </div>
            </div>
            `;

		// 打印底部内容模板
		const bottomHtml = `
            <div class="my-bottom">
              <div class="my-list-row">
                <div class="my-list-col"></div>
                <div class="my-list-col">创建人： </div>
                <div class="my-list-col">创建日期：2020-09-20</div>
              </div>
            </div>
            `;

		/**
		 * @Author: lilin_:）
		 * @name: 默认空白数组
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		let defaultBlankData = [
			{
				iswebAdd: true,
				webid: GenNonDuplicateID(),
				time: '',
				borrower: '',
				borrowerId: '', //借款人
				amount: '',
				repayment: '',
				startDate: '',
				endDate: '',
				interestRate: '',
				accruedInterest: '',
				paidInterest: '',
			},
		];
		const state: any = reactive({
			selectFrom: {
				engineeringTypeId: '', //工程类别OK
				engineeringTypeIdData: [], //工程类别数据

				contractUnitId: '', //甲方合作单位ID
				contractUnitIdData: [],

				contractId: '', //项目ID OK
				contractIdData: [], //单位搜索的数据和联系人一样

				managerId: '', //项目经理ID
				managerIdData: [],
				state: '', //状态ID 1施工中,2质保期中,3已结算
				time1: '', //时间
				time2: '', //时间
				on: 0, //默认是0，1是点击

				stateData: [
					{ label: '施工中', value: '1' },
					{ label: '质保期中', value: '2' },
					{ label: '已结算', value: '3' },
				],
				partnerId: '', //合作方ID
				partnerIdData: [],

				// -----------------------
				time: '', //时间
				contactPerson: '', //联系人
				type: '', //单位类型1供应商2客户3公司员工
				typeArry: [
					{ label: '供应商', value: '1' },
					{ label: '客户', value: '2' },
					{ label: '公司员工', value: '3' },
				], //单位类型1供应商2客户3公司员工
			},
			tableData: [], //表格数据
			selecttableData: [], //选择的数组
		});

		const selectAllChangeEvent1: VxeTableEvents.CheckboxAll = ({ checked, records }: any) => {
			console.log(checked ? '所有勾选事件' : '所有取消事件', records);
			state.selecttableData = records;
		};

		const selectChangeEvent1: VxeTableEvents.CheckboxChange = ({ checked, records }: any) => {
			console.log(checked ? '勾选事件' : '取消事件', records);
			state.selecttableData = records;
		};

		/**
		 * @Author: lilin_:）
		 * @name: 项目ID
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const getProjectName = async () => {
			let resData: any = await axios_contractselListTop();
			state.selectFrom.contractIdData = resData.obj;
			console.log(toRaw(resData.obj), '项目id');
		};

		/**
		 * @Author: lilin_:）
		 * @name: 获取借款明细
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const get_TabaDat = () => {
			let data = {
				time1: state.selectFrom.time1,
				time2: state.selectFrom.time2,
				on: state.selectFrom.on,
				engineeringTypeId: state.selectFrom.engineeringTypeId,
				contractUnitId: state.selectFrom.contractUnitId,
				contractId: state.selectFrom.contractId,
				managerId: state.selectFrom.managerId,
				state: state.selectFrom.state,
				partnerId: state.selectFrom.partnerId,
			};

			console.log(data, 'data');

			axios_receivablesselList(data).then((res) => {
				state.tableData = res.obj;
			});
		};

		const searchEvent: VxeFormEvents.Submit = async () => {
			state.selectFrom.on = 1;
			get_TabaDat();
			// VXETable.modal.message({ content: '查询事件', status: 'info' });
		};

		/**
		 * @Author: lilin_:）
		 * @name: 重置搜索表单
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const resetEvent: VxeFormEvents.Reset = async () => {
			state.selectFrom.engineeringTypeId = '';
			state.selectFrom.contractUnitId = '';
			state.selectFrom.contractId = '';
			state.selectFrom.managerId = '';
			state.selectFrom.state = '';
			state.selectFrom.partnerId = '';

			state.selectFrom.on = 0;
			state.selectFrom.time1 = '';
			state.selectFrom.time2 = '';

			await get_TabaDat();
			// VXETable.modal.message({ content: '重置事件', status: 'info' });
		};

		// 首页查询数据

		const allSelect = () => {
			getProjectName(); //项目ID
			getSelectData(); //工程类别 OK
			getSelectData2(); //甲方合同单位ID 和合作方
			getSelectData3();

			// getSelectData2(); //甲方合同单位ID   /contacts/selList?type=2
			// getSelectData3(); // 项目经理ID /contacts/selList?type=3
		};

		// 项目数据contractId

		const getSelectData = () => {
			// 工程类别ID
			axios_categoryselList({}).then((res) => {
				if (res.code == 200) {
					state.selectFrom.engineeringTypeIdData = res.obj;
					// console.log(res.obj, '工程类别ID');
				}
			});
		};

		// --------------------
		// 甲方合同单位ID 和合作方
		const getSelectData2 = () => {
			axios_SelList({
				type: 4,
			}).then((res) => {
				if (res.code == 200) {
					state.selectFrom.contractUnitIdData = res.obj;
					state.selectFrom.partnerIdData = res.obj;
					console.log(res.obj, '甲方合同单位ID');
					// 合作方id
				}
			});
		};
		// 项目经理ID
		const getSelectData3 = () => {
			axios_SelList({
				type: 3,
			}).then((res) => {
				if (res.code == 200) {
					state.selectFrom.managerIdData = res.obj;
					console.log(res.obj, '项目经理ID');
				}
			});
		};

		onMounted(() => {
			get_TabaDat();
			allSelect();

			// let a = GenNonDuplicateID()
			// console.log(a)
		});

		//实时更新
		const editClosedEvent: VxeTableEvents.EditClosed = ({ row, column }) => {
			console.log(toRaw(row), '11111');
			if (row.iswebAdd) {
				// 走保存接口
				// console.log(toRaw(row), '我是前端提交');
				axios_loanadd(row).then((res) => {
					// console.log(res, '是否啊添加');
					if (res.code == 200) {
						state.selectFrom.on = 1;

						get_TabaDat();
					}
				});
			} else {
				axios_loanup(row).then((res) => {
					if (res.code == 200) {
						state.selectFrom.on = 1;

						get_TabaDat();
					}
				});
				// console.log(toRaw(row), '我是后段提交');
			}

			const $table = xTable1.value;
			const field = column.property;
			const cellValue = row[field];
			// 判断单元格值是否被修改;
			// if ($table.isUpdateByRow(row, field)) {
			// 	setTimeout(() => {
			// 		VXETable.modal.message({
			// 			content: `局部保存成功！ ${field}=${cellValue}`,
			// 			status: 'success',
			// 		});
			// 		// 局部更新单元格为已保存状态
			// 		$table.reloadRow(row, null, field);
			// 	}, 300);
			// }
		};

		/**
		 * @Author: lilin_:）
		 * @name: 关联表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = xTable1.value;
			const $toolbar = xToolbar.value;
			$table.connect($toolbar);
		});

		/**
		 * @Author: lilin_:）
		 * @name: 新增空白行
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const addDefaultBlank = () => {
			let addArry = defaultBlankData.map((item: any) => {
				return {
					...item,
					...{
						webid: GenNonDuplicateID(),
					},
				};
			});
			state.tableData = JSON.parse(JSON.stringify([...state.tableData, ...addArry]));
			// console.log(toRaw(state.tableData), '11111111111');
			ElMessage.success({
				message: '新增1行空白栏',
				type: 'success',
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 删除数据
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const deleteTable: any = async () => {
			let webAddArry: any = [];
			let reeData: any = [];
			state.selecttableData.forEach((item: any) => {
				if (item.iswebAdd == true) {
					webAddArry.push(item);
				} else {
					reeData.push(item);
				}
			});
			// 判断前端数据是否有值
			let webDelet = () => {
				if (webAddArry.length != 0) {
					// 前端删除
					state.tableData = state.tableData.filter((item: any) => {
						return !webAddArry.find((_item: any) => _item.webid === item.webid);
					});
					// 删除方法2
					// 		state.invoiceLedgerTableData=arr;
					// 	const arr=state.invoiceLedgerTableData;
					// 		console.log(JSON.parse(JSON.stringify(arr)),'aaaaaaaaaaaaaaaaaaaaa');
					// webAddArry.forEach((item:any) => {
					// 			arr.forEach((_item,_index) => {
					// 					if(_item.webid===item.webid){
					// 							arr.splice(_index,1)
					// 					}
					// 			});
					// });
					// state.invoiceLedgerTableData=JSON.parse(JSON.stringify(arr))
				}
			};

			let resDelet = async () => {
				if (reeData.length != 0) {
					let { code }: object = await axios_loandel(
						reeData.map((item: any) => {
							return item.id;
						})
					);

					// console.log(code, '11111111');
					if (code == 200) {
						state.selectFrom.on = 0;
						get_TabaDat();
					}
				}
			};
			await resDelet();
			await webDelet();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 高级导出功能
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const funnelEvent = () => {
			const $table = xTable1.value;
			$table.openExport();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 打印表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const printTab = () => {
			const $table = xTable1.value;
			$table.print({
				sheetName: '收款明细',
				style: printStyle, //自定义样式
				columns: [
					{ field: 'engineeringType' },
					{ field: 'contractUnit' },

					{ field: 'contractName' },
					{ field: 'projectManager' },
					{ field: 'state' },
					{ field: 'partnerUnit' },

					{ field: 'managementFee' },

					{ field: 'startTime' },
					{ field: 'endTime' },
					{ field: 'warrantyPeriod' },

					{ field: 'engineeringContractMoney' },

					{ field: 'supplementalAgreementMoney' },

					{ field: 'contractSubtotal' },

					{ field: 'settleAccount' },

					{ field: 'countProgress' },

					{ field: 'receiptOfTheCurrentPeriod' },
					{ field: 'accumulativeCollection' },

					{ field: 'uncollected' },
					{ field: 'managementFeeAccount' },
					{ field: 'collectionRate' },
					{ field: 'remark' },
				],
				beforePrintMethod: ({ content }) => {
					// 拦截打印之前，返回自定义的 html 内容
					// return topHtml + content + bottomHtml;
					return content;
				},
			});
		};

		// 展示内容下拉搜索
		const getSelectLabel = (value, list) => {
			let item = list.find((item) => item.id == value);
			return item ? item.contactPerson : null;
		};

		return {
			...toRefs(state),
			editClosedEvent, //实时更新
			xToolbar, //关联表格
			xTable1, //表格
			addDefaultBlank, //新增空白行
			deleteTable, //删除数据
			funnelEvent, //导出数据
			printTab, //打印
			getSelectLabel,

			selectAllChangeEvent1,
			selectChangeEvent1,
			input: ref(''),
			searchEvent,
			resetEvent,
			transitionNumber,
		};
	},
};
</script>

<style scoped lang="scss"></style>
